<template>
  <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
import * as echarts from 'echarts'

require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    chartData: {
      type: Object,
      required: true,
      default: () => ({}) // 添加默认值
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      handler(val) {
        this.handleChartDataChange(val)
      },
      // immediate: true,
      deep: true // 添加深度监听，因为 chartData 是对象
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      // 图表初始化后，立即设置数据
      this.handleChartDataChange(this.chartData)
    },

    handleChartDataChange(val) {
      console.log("valvalvalval",val)
      // 确保图表已经初始化
      if (!this.chart) {
        return
      }
      // 验证数据有效性
      if (!val || typeof val !== 'object') {
        console.warn('Invalid chartData:', val)
        return
      }

      // 计算总数用于百分比计算
      const total = (val.total50 || 0) + (val.total5080 || 0) + (val.total80 || 0)

      const data = []

      // 始终添加所有年龄段，即使值为0
      data.push({
        value: val.total50 || 0,
        name: '50岁以下数量',
        // 自定义百分比计算
        percent: total > 0 ? ((val.total50 || 0) / total * 100).toFixed(2) : '0'
      })
      data.push({
        value: val.total5080 || 0,
        name: '50-80岁数量',
        percent: total > 0 ? ((val.total5080 || 0) / total * 100).toFixed(2) : '0'
      })
      data.push({
        value: val.total80 || 0,
        name: '80岁以上数量',
        percent: total > 0 ? ((val.total80 || 0) / total * 100).toFixed(2) : '0'
      })

      console.log('处理后的数据:', data, '原始数据:', val, '总数:', total)

      // 只有有数据时才设置选项
      if (data.length > 0) {
        this.setOptions(data, total)
      } else {
        console.warn('没有有效的数据可显示')
        this.setEmptyChart()
      }
    },

    setOptions(data, total) {
      if (!this.chart) {
        return
      }

      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            // 使用自定义的百分比而不是ECharts自动计算的
            const percent = params.data.percent
            return `${params.seriesName}<br/>${params.name}: ${params.value} (${percent}%)`
          }
        },
        legend: {
          left: 'center',
          bottom: '10',
          data: data.map(item => item.name) // 动态生成图例数据
        },
        series: [
          {
            name: '人员比例',
            type: 'pie',
            roseType: 'radius',
            radius: [15, 95],
            center: ['50%', '38%'],
            data: data,
            animationEasing: 'cubicInOut',
            animationDuration: 2600,
            // 添加标签显示，使用自定义百分比
            label: {
              show: true,
              formatter: (params) => {
                return `${params.name}: ${params.value} (${params.data.percent}%)`
              }
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }, true) // 添加 true 参数表示不合并选项，直接替换
    },

    // 设置空图表状态
    setEmptyChart() {
      if (!this.chart) {
        return
      }

      this.chart.setOption({
        title: {
          text: '暂无数据',
          left: 'center',
          top: 'center',
          textStyle: {
            color: '#999',
            fontSize: 14
          }
        },
        series: [{
          type: 'pie',
          data: []
        }]
      })
    }
  }
}
</script>
